"""性能监控（QPS/延迟阈值判断）"""
"""性能监控（QPS/延迟阈值判断）"""
import time
import threading
from collections import deque
from typing import Dict, Any, List, Tuple
from fin_senti_entity_platform.utils.logger import Logger
from fin_senti_entity_platform.utils.constants import SERVICE_MONITOR_THRESHOLDS, PERFORMANCE_METRICS
from fin_senti_entity_platform.utils.config_loader import ConfigLoader


class PerformanceMonitor:
    """性能监控器类，用于监控服务性能指标并判断是否需要降级"""
    
    def __init__(self):
        """初始化性能监控器"""
        self.logger = Logger().get_logger(__name__)
        self.config = ConfigLoader().get_config('service', 'degradation')
        self.enabled = self.config.get('enabled', False)
        
        # 阈值配置
        self.latency_threshold = self.config.get('threshold', {}).get('latency', SERVICE_MONITOR_THRESHOLDS['latency'])
        self.error_rate_threshold = self.config.get('threshold', {}).get('error_rate', SERVICE_MONITOR_THRESHOLDS['error_rate'])
        
        # 性能指标队列
        self.latency_history = deque(maxlen=100)  # 保存最近100个请求的延迟
        self.error_history = deque(maxlen=1000)  # 保存最近1000个请求的错误状态
        
        # 计数器
        self.total_requests = 0
        self.total_errors = 0
        self.start_time = time.time()
        
        # 降级状态
        self.is_degraded = False
        self.degradation_reasons = []
        
        # 锁和线程
        self._lock = threading.Lock()
        self._running = False
        self._check_interval = 5  # 每5秒检查一次性能指标
    
    def record_request(self, latency: float, is_error: bool = False):
        """记录请求的性能指标
        
        Args:
            latency: 请求延迟（毫秒）
            is_error: 是否为错误请求
        """
        with self._lock:
            self.latency_history.append(latency)
            self.error_history.append(is_error)
            self.total_requests += 1
            if is_error:
                self.total_errors += 1
    
    def get_current_metrics(self) -> Dict[str, float]:
        """获取当前性能指标
        
        Returns:
            Dict[str, float]: 性能指标字典
        """
        with self._lock:
            # 计算QPS
            elapsed_time = max(1.0, time.time() - self.start_time)
            qps = self.total_requests / elapsed_time
            
            # 计算平均延迟
            avg_latency = sum(self.latency_history) / len(self.latency_history) if self.latency_history else 0
            
            # 计算错误率
            error_rate = sum(self.error_history) / len(self.error_history) if self.error_history else 0
            
            return {
                'qps': qps,
                'avg_latency': avg_latency,
                'error_rate': error_rate,
                'total_requests': self.total_requests,
                'total_errors': self.total_errors
            }
    
    def check_degradation_conditions(self) -> Tuple[bool, List[str]]:
        """检查是否满足降级条件
        
        Returns:
            Tuple[bool, List[str]]: (是否需要降级, 降级原因)
        """
        if not self.enabled:
            return False, []
        
        metrics = self.get_current_metrics()
        reasons = []
        
        # 检查延迟是否超过阈值
        if metrics['avg_latency'] > self.latency_threshold:
            reasons.append(f"平均延迟 ({metrics['avg_latency']:.2f}ms) 超过阈值 ({self.latency_threshold}ms)")
        
        # 检查错误率是否超过阈值
        if metrics['error_rate'] > self.error_rate_threshold:
            reasons.append(f"错误率 ({metrics['error_rate']:.4f}) 超过阈值 ({self.error_rate_threshold})")
        
        return len(reasons) > 0, reasons
    
    def start_monitoring(self):
        """启动性能监控"""
        if not self._running and self.enabled:
            self._running = True
            self._monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
            self._monitor_thread.start()
            self.logger.info("性能监控已启动")
    
    def stop_monitoring(self):
        """停止性能监控"""
        if self._running:
            self._running = False
            if hasattr(self, '_monitor_thread'):
                self._monitor_thread.join(timeout=2.0)
            self.logger.info("性能监控已停止")
    
    def _monitor_loop(self):
        """监控循环"""
        while self._running:
            should_degrade, reasons = self.check_degradation_conditions()
            
            with self._lock:
                if should_degrade != self.is_degraded:
                    self.is_degraded = should_degrade
                    self.degradation_reasons = reasons
                    
                    if should_degrade:
                        self.logger.warning(f"服务进入降级状态: {'; '.join(reasons)}")
                    else:
                        self.logger.info("服务恢复正常状态")
            
            time.sleep(self._check_interval)
    
    def get_degradation_status(self) -> Dict[str, Any]:
        """获取当前降级状态
        
        Returns:
            Dict[str, Any]: 降级状态信息
        """
        with self._lock:
            return {
                'is_degraded': self.is_degraded,
                'reasons': self.degradation_reasons,
                'metrics': self.get_current_metrics(),
                'thresholds': {
                    'latency': self.latency_threshold,
                    'error_rate': self.error_rate_threshold
                }
            }


# 创建全局实例
global_performance_monitor = PerformanceMonitor()


def get_performance_monitor() -> PerformanceMonitor:
    """获取性能监控器实例"""
    return global_performance_monitor